#include <windows.h>
#include <tlhelp32.h> //声明快照函数文件
#include "stdio.h"
#include <cstring>
#include <iostream>
// 根据进程ID， 返回指定进程下"第一个"窗口的窗口句柄
// 注: 此程序还不够完善, 因为指定进程下可能有多个窗口
HWND GetWindowHandleByPID(DWORD dwProcessID)
{
	HWND h = GetTopWindow(0);
	while (h)
	{
		DWORD pid = 0;
		DWORD dwTheardId = GetWindowThreadProcessId(h, &pid);

		if (dwTheardId != 0)
		{
			if (pid == dwProcessID /*your process id*/)
			{
				// here h is the handle to the window
				return h;
			}
		}

		h = GetNextWindow(h, GW_HWNDNEXT);
	}

	return NULL;
}

int main(int argc, char *argv[])
{
	PROCESSENTRY32 pe32;
	std::string serverName;
	if (argv > 0)
	{
		serverName = argv[1];
	}
	else
	{
		std::cout << "no servername " << std::endl;
		return 0;
	}
	std::cout << " servername " << serverName.c_str() << std::endl;

GoBack:
	//在使用这个结构之前，先设置它的大小
	pe32.dwSize = sizeof(pe32);

	//给系统内的所有进程拍一个快照
	HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

	//Includes the process list in the snapshot
	if (hProcessSnap == INVALID_HANDLE_VALUE)
	{
		printf("CreateToolhelp32Snapshot 调用失败! n");
		return -1;
	}

	//遍历进程快照，轮流显示每个进程信息
	BOOL bMore = ::Process32First(hProcessSnap, &pe32);
	while (bMore)
	{
		// printf(" 进程名称为:%s\n", pe32.szExeFile);
		// printf(" 进程ID为:%u \n\n", pe32.th32ProcessID);

		if (_stricmp(pe32.szExeFile, "WerFault.exe") == 0)
		{
			printf(" 进程名称为:%s\n", pe32.szExeFile);
			printf(" 进程ID为 :%u \n\n", pe32.th32ProcessID);

			HWND hwnd = GetWindowHandleByPID(pe32.th32ProcessID);
			if (hwnd)
			{
				char szText[256] = {0};
				GetWindowText(hwnd, szText, 256);
				// 自己崩溃程序的"进程名"
				if (_stricmp(szText, serverName.c_str()) == 0)
				{
					printf("Text: %s\n\n", szText);

					// 关闭"xx程序已停止"提示窗口
					SendMessage(hwnd, WM_CLOSE, NULL, NULL);
				}
			}
		}

		//遍历下一个
		bMore = ::Process32Next(hProcessSnap, &pe32);
	}
	//清除snapshot对象
	::CloseHandle(hProcessSnap);
	Sleep(10 * 1000);
	std::cout << "go back " << std::endl;
	goto GoBack;

	return 0;
}